package result

import (
	"github.com/gin-gonic/gin"
	"inspector/pkg/errors"
	"inspector/pkg/i18n"
	"net/http"
	"strings"
)

type APIResponse struct {
	Success bool        `json:"success"`
	Message string      `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
	Error   *APIError   `json:"error,omitempty"`
}

type APIError struct {
	Code    int                    `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
}

func SendResponse(c *gin.Context, data interface{}, err *errors.Error) {
	statusCode := http.StatusOK
	langHeader := c.GetHeader("Accept-Language")
	lang := getPreferredLanguage(langHeader)
	if err != nil {
		statusCode = err.HTTPCode

		response := &APIResponse{
			Success: false,
			Message: err.Error(),
			Error: &APIError{
				Code:    err.Code,
				Message: i18n.Translate(err.Message, lang),
			},
		}

		if err.Expose {
			response.Error.Details = err.Details
		}

		c.JSON(statusCode, response)
	} else {
		response := &APIResponse{
			Success: true,
			Data:    data,
		}
		c.JSON(statusCode, response)
	}
}

func getPreferredLanguage(headerValue string) string {
	parts := strings.Split(headerValue, ",")
	for _, part := range parts {
		lang := strings.Split(part, ";")[0]
		lang = strings.ToLower(strings.TrimSpace(lang))
		if lang == "zh" || strings.HasPrefix(lang, "zh-") {
			return "zh"
		}
	}
	return "en"
}
